import { login, logout, getInfo,vercode } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, vercode,key } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, vercode: vercode.trim(),key: key })
        .then(response => {
          commit('SET_TOKEN', response.access_token)
          setToken(response.access_token)
          resolve(response)
        }).catch(error => {
          console.log('error=>', error)
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      let para = {
          token: state.token
      };
      getInfo(para).then(response => {
        // const {code, data,message,result } = response

        console.log("getinfo",response)
        let user = response.result;
        user.uRealName=user.name
        user.uLoginName=user.name;
        user.uID=user.id;
        window.localStorage.user = JSON.stringify(user);

        console.log(" response.data.roles", response.data.roles);

        // if (!data) {
        //   reject('Verification failed, please Login again.')
        // }

        if (response.result.id == 0) {
          return reject('Verification failed, please Login again.')
        }

        // const { roles, name, avatar } = response.data
        let name = response.result.name;
        let avatar = response.result.avatar;
        let roles = response.data.roles;
        if(avatar.startsWith("/")){
          avatar = "https://www.6years.org" + avatar;
        }
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // var loginParams = { uid: user.id };
        // getNavigationBar(loginParams).then(data => {
        //   console.log("getNavigationBar data=>",data);
        //     if (data.success) {
        //         console.info('%c get navigation bar from api succeed!', "color:red")
        //         let getRouter = data.response.children//后台拿到路由
        //         console.log(data);
        //         //router.addRoutes(getRouter);
        //     }
        // });

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  vercode({ commit }) {
    return new Promise(resolve => {
      vercode().then((response)=>{
        resolve(response)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
